package com.example.carrierapp.util;

import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.example.carrierapp.ui.view.recycleview.XRecyclerView;


/**
 * Created by evan on 2017/11/2.
 * gradview的 行距
 */
public class GridSpacingItemDecoration extends RecyclerView.ItemDecoration {

    private int spanCount;
    private int spacing;
    private boolean includeEdge;

    public GridSpacingItemDecoration(int spanCount, int spacing, boolean includeEdge) {
        this.spanCount = spanCount;
        this.spacing = spacing;
        this.includeEdge = includeEdge;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        RecyclerView.Adapter adapter = parent instanceof XRecyclerView ? ((XRecyclerView) parent).getWrapAdapter() :
                parent.getAdapter();
        int position = parent.getChildAdapterPosition(view); // item position
        if (adapter.getItemViewType(position) > 10000) {
            outRect.set(0, 0 , 0, 0);
            return;
        }
        position = parent instanceof XRecyclerView ? position - 1 : position;

        int column = position % spanCount; // item column
        int row = (position) / spanCount;
        int right = 0;
        int top = 0;
        if (column + 1 == spanCount) {
            right = spacing;
        }
        if (row > 0) {
            top = spacing;
        }
        outRect.set(spacing, top, right, 0);
//        if ((position + 1) % spanCount > 0) {
//            outRect.set(spacing, 0,0, 0);
//        } else {
//            outRect.set(spacing, 0, spacing, 0);
//        }
//        if (row > 0) {
//            outRect.top = spacing;
//        }
//        if (includeEdge) {
//            outRect.left = spacing - column * spacing / spanCount; // spacing - column * ((1f / spanCount) * spacing)
//            outRect.right = (column + 1) * spacing / spanCount; // (column + 1) * ((1f / spanCount) * spacing)
//
//            if (position < spanCount) { // top edge
////                outRect.top = spacing;
//            }
//            outRect.bottom = spacing; // item bottom
//        } else {
//            outRect.left = column * spacing / spanCount; // column * ((1f / spanCount) * spacing)
//            outRect.right = spacing - (column + 1) * spacing / spanCount; // spacing - (column + 1) * ((1f /    spanCount) * spacing)
//            if (position >= spanCount) {
//                outRect.top = spacing; // item top
//            }
//        }
    }
}
